﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Diagnostics;

namespace Eugenhome.Atrium
{
    /// <summary>
    /// 
    /// </summary>
    public class Login
    {
        /// <summary></summary>
        private const string PRIVATEKEYNAME = "SignContent";

        /// <summary></summary>
        private const string KEYPRIVATEKEY = "aadlskdjölj8a9sf$%$kjlöia890f()laksjd";

        /// <summary></summary>
        private string _serverMapPath = "";

        /// <summary></summary>
        private CCryptography _serviceCry = new CCryptography(KEYPRIVATEKEY);

        /// <summary></summary>
        private CCryptography _userCry;

        /// <summary></summary>
        private string SignFullFileName { get { return Path.Combine(_serverMapPath, "sign.txt"); } }

        /// <summary></summary>
        public bool SignFileExists { get { return File.Exists(SignFullFileName); } }

        /// <summary></summary>
        private string _encryptedUserKey;

        /// <summary></summary>
        public string DecryptedUserKey;

        /// <summary></summary>
        public bool Valid = false;

        /// <summary>
        /// 
        /// </summary>
        public Login()
        {
            _serverMapPath = HttpContext.Current.Server.MapPath("");
            _encryptedUserKey = HttpContext.Current.Request.Cookies[PRIVATEKEYNAME] != null ? HttpContext.Current.Request.Cookies[PRIVATEKEYNAME].Value : null;

            CheckPrivateKey(_encryptedUserKey);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private bool CheckPrivateKey(string key)
        {
           // if (Debugger.IsAttached) return true;

            if (key == null) return false;

            if (!SignFileExists) return false;

            DecryptedUserKey = _serviceCry.Decrypt64(key);
            DecryptedUserKey = (DecryptedUserKey == null) ? key : DecryptedUserKey;

            _userCry = new CCryptography(DecryptedUserKey);

            Valid = _userCry.FileCrypted(SignFullFileName);
            return Valid;
        }

        /// <summary>
        /// 
        /// </summary>
        public void Check()
        {
            if (!Valid)
            {
                HttpContext.Current.Response.Redirect("login.aspx?url=" + HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.ServerVariables["url"]));
                HttpContext.Current.Response.End();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userkey"></param>
        public bool Check(string userkey)
        {
            bool result = CheckPrivateKey(userkey);// userkey.Equals(DecryptedUserKey);

            if (result)
            {
                _encryptedUserKey = _serviceCry.Encrypt64(userkey);
                
                SetCookies();
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newkey"></param>
        /// <returns></returns>
        public bool SetNewPrivateKey(string newkey)
        {
            if (Valid)
            {
                string content = "";

                Random rnd = new Random();
                for (int i = 0; i < 25; i++) content += rnd.Next(10, 20).ToString();

                try
                {
                    StreamWriter sw = File.CreateText(SignFullFileName);
                    sw.Write(content);
                    sw.Close();

                }
                catch { return false; }

                DecryptedUserKey = newkey;
                _encryptedUserKey = _serviceCry.Encrypt64(DecryptedUserKey);

                _userCry = new CCryptography(DecryptedUserKey);

                _userCry.FileEncrypt(SignFullFileName);

                SetCookies();
            }

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        private void SetCookies()
        {
            HttpContext.Current.Response.Cookies[PRIVATEKEYNAME].Value = _encryptedUserKey;
            HttpContext.Current.Response.Cookies[PRIVATEKEYNAME].Expires = DateTime.Now.AddMonths(6);
        }

        /// <summary>
        /// 
        /// </summary>
        public void Logout()
        {
            HttpContext.Current.Response.Cookies[Login.PRIVATEKEYNAME].Expires = DateTime.Now.AddMinutes(-1);
        }

        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool DecryptFile(string filename)
        {
            return _userCry.FileDecrypt(filename);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool EncryptFile(string filename)
        {
            return _userCry.FileEncrypt(filename);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string DecryptContent(string filename)
        {
            string result = "";
            try
            {
                byte[] daten = File.ReadAllBytes(filename);

                byte[] daten2 = new byte[0];

                daten2 = _userCry.Decrypt(daten);

                result = Encoding.ASCII.GetString(daten2);
            }
            catch { }

            return result;
        }
    }
}
